#!/bin/sh

DAEMON=wsd_simple_server
ONVIF_CONFIG=/etc/onvif.conf
ONVIF_WEBUI_CONF=/etc/webui/onvif.conf
PRUDYNT_CONFIG=/etc/prudynt.cfg

. /usr/share/common

iface="$(iface_default)"

model=$(awk -F '=' '/^IMAGE_ID=/ {print $2}' $OS_RELEASE_FILE)

# extract iface for daemon from onvif.conf
DAEMON_ARGS="-i $iface -x http://%s/onvif/device_service -m $model -n thingino -p /run/$DAEMON_SHORT.pid"

# read web config, create if missing
[ -d $(dirname $ONVIF_WEBUI_CONF) ] || mkdir -p $(dirname $ONVIF_WEBUI_CONF)
[ -f $ONVIF_WEBUI_CONF ] || touch $ONVIF_WEBUI_CONF
. $ONVIF_WEBUI_CONF

update_config() {
	local current file key value
	file=$1
	key=$2
	value=$3
	current=$(awk -F= -v key="$key" '$1==key {print $2}' $file)
	[ -z "$value" ] && value="0"
	[ "$current" = "$value" ] && return
	sed -i "s/^$key=.*/$key=$value/" $file
}

start() {
	echo_title "Starting ONVIF discovery"

	if ! is_gateway_reachable; then
		echo_error "Disabled"
		exit 1
	fi

	if is_streamer_disabled; then
		echo_error "Streamer disabled"
		exit 1
	fi

	start_daemon

	if grep -q "^# GENERATED" $ONVIF_CONFIG; then
		echo_info "Config already generated"
		return
	fi

	tempfile=$(mktemp -u)
	cp $ONVIF_CONFIG $tempfile
	update_config $tempfile "model" "$model"
	update_config $tempfile "hardware_id" "ingenic_$SOC_MODEL"
	update_config $tempfile "serial_num" "$(fw_printenv -n ethaddr | sed 's/://g')"
	update_config $tempfile "firmware_ver" "$BUILD_ID"
	update_config $tempfile "ifs" "$iface"
	update_config $tempfile "user" "$(awk -F '"' '/username:/ {print $2}' $PRUDYNT_CONFIG)"
	update_config $tempfile "password" "$(awk -F '"' '/password:/ {print $2}' $PRUDYNT_CONFIG)"
	update_config $tempfile "ptz" "$([ -n "$gpio_motor_h" ] && echo 1 || echo 0)"
	update_config $tempfile "max_step_x" "$motor_maxstep_h"
	update_config $tempfile "max_step_y" "$motor_maxstep_v"
	update_config $tempfile "move_right" "motors -d h -x $motor_maxstep_h"
	update_config $tempfile "move_down" "motors -d h -y $motor_maxstep_v"
	sed -i '1i # GENERATED On '"$(date)" $tempfile
	mv $tempfile $ONVIF_CONFIG
}

stop() {
	echo_title "Stopping ONVIF discovery"

	stop_daemon
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac

exit 0
